const showTime = tag => {
    let date, hour, minute, second;
    let format = time => {
        return time < 10 ? "0" + time : time;
    };

    setInterval(() => {
        date = new Date();
        hour = format(date.getHours());
        minute = format(date.getMinutes());
        second = format(date.getSeconds());
        tag.text(hour + ":" + minute + ":" + second);
    }, 1000);
};

$(() => {
    let tags = {
        time: $('.time'),
        userName: $('#user-name'),
        password: $('#password'),
        submit: $('#login-submit')
    };
    //time
    showTime(tags.time);

    //login
    tags.submit.click(() => {
        let data = {
            username: tags.userName.val().trim(),
            password: tags.password.val().trim()
        };

        //http://www.fjemiot.cn/erp/login?userNo=U2019001&password=1234567
        if (!(data.name === '' || data.password === '')) {
            $.ajax({
                url: 'http://www.fjemiot.cn/erp/login',
                type: 'post',
                data: 'userNo='+data.username+'&password='+data.password,
                dataType: 'text',
                success: (reply) => {
                    if (reply.trim() == '') {
                        tip.alert('帐号或密码错误','登录', 'error');
                    } else {
                        let user = JSON.parse(reply);
                        cookie.setCookie('user', user['userNo']);
                        cookie.write();
                        cookie.setCookie('power', user['type']);
                        cookie.write();
                        window.location.href = '/erp';
                    }
                },
                error: (reply) => {
                    console.log(reply);
                }
            });
        } else {
            tip.alert('帐号或者密码不能为空', '登录警告', 'warn');
        }
    });

    //输入用户编号，回车使密码框聚焦
    tags.userName.keydown((e) => {
        if (e.key == 'Enter') tags.password.focus();
    });

    //密码框回车点击登录按钮
    tags.password.keydown((e) => {
        if (e.key == 'Enter') tags.submit.click();
    });
});